﻿var clientDetailExpanded = true;
var dropFrameExpanded = false;

function HasInfo() {
    var clientInfo = false;
    var categoryInfo = false;
    var serviceInfo = false;
}

$(document).ready(function () {

    $('input[type="text"]').addClass("ui-corner-all");
    $(':submit').button();

    $('.button').hover(
	function () {
	    $(this).addClass("ui-state-hover");
	},
	function () {
	    $(this).removeClass("ui-state-hover");
	});

    $('#client_list #search_box .button').click(function () {
        doSearch();
    });

    $('body').keypress(function (e) {
        if (e.keyCode == 13) {
            doSearch();
            e.preventDefault();
        }
    });

    $('#client_list #search_box input:text').focus();
    $('#result_list .panelContent').html('');

    $('#client_detail .panelTitle span.close').click(function () {
        $('#client_detail').fadeOut(500);
    });
    $('#client_detail .panelTitle span.minimise').click(function () {
        if (clientDetailExpanded) {
            colapseClientDetail();
        }
        else {
            expandClientDetail();
        }
    });

    $('#result_list .panelTitle span.expand').click(function () {
        if (dropFrameExpanded) {
            colapseDropFrame();
        }
        else {
            expandDropFrame();
        }
    });

    $('#btnSearch').click(function () {
        doSearch();
    });

    $('#btnSaveAll').click(function () {
        $('#drop_loader').showLoading();
    });
});

function doSearch() {
    //$('#client_list').showLoading();
    $('#result_list_loader').showLoading();

    //Do an AJAX call to get client list
    var searchString = $('#client_list #search_box input:text').val();
    $.ajax({
        type: 'POST',
        url: 'Advance.aspx/SearchClientByName',
        data: '{"name":"' + searchString + '"}',
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (msg) {
            //Parse the JSON result and process
            var obj = jQuery.parseJSON(msg.d)
            buildClientList(obj);
        },
        error: function (xml, textStatus, errorThrown) {
            alert(xml.status + "||" + xml.responseText);
        }
    });
}

function buildClientList(obj) {
    if (obj.length > 0) {
        var list = '<ul>';
        for (var i = 0; i < obj.length; i++) {
            list += '<li clientid="' + obj[i].Id + '" dob="' + obj[i].Dob + '" gender="' + obj[i].Gender + '">' + obj[i].FirstName + ', ' + obj[i].LastName + '</li>';
        }
        list += '</ul>';
        $('#result_list .panelContent').html(list);
    }
    else {
        $('#result_list .panelContent').html('');
    }

    $('#result_list_loader').hideLoading();

    $('#client_list #search_box input:text').focus().select();

    $('#result_list li').css('border', '1px solid #a9a9a9').hover(
    function () {
        $(this).addClass("ui-state-hover");
    },
    function () {
        $(this).removeClass("ui-state-hover");
    }).click(function () {
        $('#result_list li').each(function () {
            $(this).removeClass("ui-state-highlight");
        });
        $(this).addClass("ui-state-highlight");
        displayClientInfo($(this));
    });

    if (dropFrameExpanded) {
        enableClientDragging(true);
    }
}

function displayClientInfo(item) {
    $('#txtId').text(item.attr('clientid'));
    $('#txtFirstName').text($.trim(item.text().split(',')[0]));
    $('#txtLastName').text($.trim(item.text().split(',')[1]).toUpperCase());
    $('#txtDOB').text(item.attr('dob'));
    $('#txtGender').text(item.attr('gender'));
    $('#client_detail').stop().fadeIn(500, function () {
        expandClientDetail();
    });
}

function colapseClientDetail() {
    $('#client_detail .panelContent').slideUp();
    $('#client_detail .panelTitle span.minimise').removeClass('ui-icon-circle-triangle-n').removeClass('ui-icon-circle-triangle-s').addClass('ui-icon-circle-triangle-s');
    clientDetailExpanded = false;
}

function expandClientDetail() {
    $('#client_detail .panelContent').slideDown();
    $('#client_detail .panelTitle span.minimise').removeClass('ui-icon-circle-triangle-s').removeClass('ui-icon-circle-triangle-n').addClass('ui-icon-circle-triangle-n');
    clientDetailExpanded = true;
}

function colapseDropFrame() {
    $('#step_1_title').html('&nbsp;');
    $('#step_1_wrapper').css('display', 'none');
    enableClientDragging(false);
    $('#drop_wrapper').stop().animate({
        width: '0px'
    }, 200, function () {
        $(this).css('display', 'none');
    });
    $('#result_list .panelTitle span.expand').removeClass('ui-icon-circle-triangle-w').removeClass('ui-icon-circle-triangle-e').addClass('ui-icon-circle-triangle-e');
    dropFrameExpanded = false;
}

function expandDropFrame() {
    if ($('#result_list .panelContent').html() == '') {
        $.showGrowlMessage(GrowlType.INFO, 'Please search for clients first');
        return false;
    }

    enableClientDragging(true);

    $('#drop_wrapper').css('display', 'block').stop().animate({
        width: '745px'
    }, 500, function () {
        $('#step_1_title').html('STEP 1 - Drag & Drop a Client here to start');
        if (HasInfo.clientInfo)
            $('#step_1_wrapper').fadeIn();
    });

    $('#result_list .panelTitle span.expand').removeClass('ui-icon-circle-triangle-w').removeClass('ui-icon-circle-triangle-e').addClass('ui-icon-circle-triangle-w');
    dropFrameExpanded = true;
}

function enableClientDragging(enabled) {
    if (enabled) {
        $('#result_list li').draggable({
            opacity: 1.0,
            helper: "clone",
            start: function (e, ui) {
                $(ui.helper).removeClass().addClass("ui-state-hover ui-draggable-helper");
                $('#step_1_wrapper').fadeOut();
            },
            stop: function (e, ui) {
                if (HasInfo.clientInfo)
                    $('#step_1_wrapper').fadeIn();
            }
        });

        $('#drop_wrapper .panelContent').droppable({
            accept: '#result_list li',
            activeClass: 'ui-state-highlight',
            drop: clientDropped
        });
    }
    else {
        $('#result_list li').draggable('destroy');
        $('#drop_wrapper .panelContent').droppable('destroy');
    }
}

function clientDropped(evt, ui) {
    //Init
    HasInfo.clientInfo = true;
    clearDeliveryPlan();
    $(this).addClass("ui-state-highlight");
    $('#service_category_list .panelContent').html('');

    $('#service_list .panelContent').html('');
    $('#service_category_list li').draggable('destroy');
    $('#service_category_drop .panelContent').droppable('destroy').removeClass('ui-state-highlight');

    $('#drop_loader').showLoading();

    $('#step_1_wrapper').fadeIn(500,
    function () {
        var dragItem = $(ui.draggable);
        $('#client_info').html(dragItem.html() + ' - ' + dragItem.attr('clientid'));

        //Do an AJAX call to get category list
        $.ajax({
            type: 'POST',
            url: 'Advance.aspx/GetAllServiceCategories',
            data: '{}',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: function (msg) {
                //Parse the JSON result and process
                var obj = jQuery.parseJSON(msg.d)
                buildServiceCategoryList(obj);
            },
            error: function (xml, textStatus, errorThrown) {
                alert(xml.status + "||" + xml.responseText);
            }
        });
    });
}

function buildServiceCategoryList(obj) {
    if (obj.length > 0) {
        var list = '<ul>';
        for (var i = 0; i < obj.length; i++) {
            list += '<li scid="' + obj[i].Id + '" sccode="' + obj[i].Code + '">' + obj[i].Name + '</li>';
        }
        list += '</ul>';
        $('#service_category_list .panelContent').html(list);
    }
    else {
        $('#service_category_list .panelContent').html('');
    }

    $('#service_category_list li').css('border', '1px solid #a9a9a9').hover(
    function () {
        $(this).addClass("ui-state-hover");
    },
    function () {
        $(this).removeClass("ui-state-hover");
    });

    $('#drop_loader').hideLoading();

    //Enable dragging
    $('#service_category_list li').draggable({
        opacity: 1.0,
        helper: "clone",
        start: function (e, ui) {
            $(ui.helper).removeClass().addClass("ui-state-hover ui-draggable-helper");
            $('#step_2_wrapper').fadeOut();
        },
        stop: function (e, ui) {
            if (HasInfo.categoryInfo)
                $('#step_2_wrapper').fadeIn();
        }
    });

    $('#service_category_drop .panelContent').droppable({
        greedy: true,
        accept: '#service_category_list li',
        activeClass: 'ui-state-highlight',
        drop: categoryDropped
    });
}

function categoryDropped(evt, ui) {
    HasInfo.categoryInfo = true;
    clearDeliveryPlan();
    $(this).addClass("ui-state-highlight");
    var categoryId = $(ui.draggable).attr('scid');

    $('#service_category_loader').showLoading();

    //Do an AJAX call to get service list
    $.ajax({
        type: 'POST',
        url: 'Advance.aspx/GetAllServices',
        data: '{"categoryId":"' + categoryId + '"}',
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (msg) {
            //Parse the JSON result and process
            var obj = jQuery.parseJSON(msg.d)
            buildServiceList(obj);
        },
        error: function (xml, textStatus, errorThrown) {
            alert(xml.status + "||" + xml.responseText);
        }
    });
}

function buildServiceList(obj) {
    if (obj.length > 0) {
        var list = '<ul>';
        for (var i = 0; i < obj.length; i++) {
            list += '<li class="serviceItem ui-state" sevid="' + obj[i].Id + '" sevcode="' + obj[i].Code + '" sevname="' + obj[i].Name + '">' + obj[i].Code + '</li>';
        }
        list += '</ul>'
        $('#service_list .panelContent').html(list);
    }
    else {
        $('#service_list .panelContent').html('');
    }

    $('#service_list li').css('border', '1px solid #a9a9a9').hover(
    function () {
        $(this).addClass("ui-state-hover");
    },
    function () {
        $(this).removeClass("ui-state-hover");
    });

    $('#service_category_loader').hideLoading();

    //Enable dragging
    $('#service_list li').draggable({
        opacity: 1.0,
        helper: "clone",
        start: function (e, ui) {
            $(ui.helper).removeClass().addClass("ui-state-hover ui-draggable-helper");
            $('#step_3_wrapper').fadeOut();
        },
        stop: function (e, ui) {
            if (HasInfo.serviceInfo)
                $('#step_3_wrapper').fadeIn();
        }
    }).hover(
    function () {
        toggleServiceDetails($(this), true);
    },
    function () {
        toggleServiceDetails($(this), false);
    });

    $('#delivery_plan .panelContent').droppable({
        greedy: true,
        accept: '#service_list li',
        activeClass: 'ui-state-highlight',
        drop: serviceDropped
    });
}

function serviceDropped(evt, ui) {
    HasInfo.serviceInfo = true;
    $(this).addClass("ui-state-highlight");

    $('#txtService').html($(ui.draggable).attr('sevname'));
    $('#cboStaff').combobox().removeClass('ui-widget-content');
    $("#txtStartDate").datepicker();
    $("#txtEndDate").datepicker();
    $("#txtTimeFrom").timepicker({});
    $("#txtTimeTo").timepicker({});
    $("#chkSchedule").buttonset();

    $("#chkSchedule label").css('width', '50px');
}

function clearDeliveryPlan() {
    $('#step_3_wrapper').css('display', 'none');
}

function toggleServiceDetails(service, show) {
    if (show) {
        $('#service_tooltip').stop(true, true).fadeIn();
        //Move to tool tip into position
        var cssObj = {
            //'display': 'block',
            'top': service.offset().top - 80,
            'left': service.offset().left - 0
        }

        $('#service_tooltip').css(cssObj);
        $('#txtSevId').html(service.attr('sevid'));
        $('#txtSevName').html(service.attr('sevname'));
        $('#txtSevCode').html(service.attr('sevcode'));
    }
    else {
        //$('#service_tooltip').css('display', 'none');
        $('#service_tooltip').stop(true, true).fadeOut();
    }
}